package com.utn.ab.config;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.util.SocketUtils;
import redis.embedded.RedisExecProvider;
import redis.embedded.RedisServer;
import redis.embedded.util.OS;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.IOException;

/**
 * @创建人 liuchunlin
 * @创建时间 15:07
 * @描述
 */
@Configuration
@Profile("test")
public class RedisConfig {
    private RedisServer redisServer;

    @Value("localhost")
    private String redisHost;

//    @Value("${random.int[58000,60000]}")
//    private int redisPort;
    int redisPort = SocketUtils.findAvailableTcpPort();

    @Bean
    RedissonClient redisson(){
        Config config = new Config();
        String prefix = "redis://";

        config.useSingleServer()
                .setAddress(prefix + redisHost + ":" + redisPort);
        return Redisson.create(config);
    }

//    @Bean
//    @Primary
//    JedisConnectionFactory jedisConnectionFactory() {
//        JedisConnectionFactory factory = new JedisConnectionFactory(
//                new RedisStandaloneConfiguration(redisHost, redisPort)
//        );
//        return factory;
//    }

    @PostConstruct
    public void startRedis() throws IOException {
        redisServer = new RedisServer(redisPort);
//        RedisExecProvider customProvider = RedisExecProvider.defaultProvider()
//                .override(OS.UNIX, "/var/unix/redis");

        //RedisExecProvider redisExecProvider = RedisExecProvider.defaultProvider();

        redisServer = RedisServer
                .builder()
        //        .redisExecProvider(redisExecProvider)
                .port(redisPort)
//        RedisExecProvider redisExecProvider = RedisExecProvider.defaultProvider();
               // .setting("daemonize no")
               // .setting("appendonly no")
                .setting("maxmemory 128M")
                .setting("bind 127.0.0.1")
                .build();
        redisServer.start();
    }

    @PreDestroy
    public void stopRedis() {
        redisServer.stop();
    }
}
